<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="角色名称：">
        <el-input v-model="listQuery.q_rolesName" style="width: 200px" size="small" class="filter-item"
          maxlength="50" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="small" type="primary" @click="check">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-table-margin">
      <el-button size="small" type="primary" @click="addRole" v-permission="['admin/system/role/save']">添加</el-button>
      <el-button size="small" type="primary" @click="editRole" v-permission="['admin/system/role/update']">修改
      </el-button>
      <el-button size="small" type="primary" @click="del" v-permission="['admin/system/role/del']">删除</el-button>
      <el-button size="small" type="primary" @click="role" v-permission="['admin/system/role/saveRoleRes']">分配权限
      </el-button>
    </div>
    <el-table ref="singleTable" :data="dataList" v-loading="listLoading" border fit highlight-current-row
      style="width: 100%" @current-change="handleCurrentChange">
      <el-table-column type="index" align="center" width="50">
      </el-table-column>
      <el-table-column property="rolesName" label="角色名称" show-overflow-tooltip> </el-table-column>
      <el-table-column label="角色描述" property="content" show-overflow-tooltip> </el-table-column>
      <el-table-column property="createTime" label="创建时间">
      </el-table-column>
      <el-table-column property="updateTime" width="200" label="更新时间">
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
    <el-dialog title="分配权限" :visible.sync="dialogVisible" destroy-on-close width="30%">
      <el-table ref="roleTable" :data="roleList" v-loading="treeLoad" border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id" highlight-current-row
        style="width: 100%" height="350px" :show-header="false" @select="select" @selection-change="handleRoleChange">
        <el-table-column type="selection" width="50" align="center"> </el-table-column>
        <el-table-column property="content" label="列表名称"> </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateRoleName">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="judgmentTitle" :visible.sync="dialogFormVisible" width="70%">
      <div class="app-container">
        <el-row>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
            class="demo-ruleForm el-form-bottom">
            <el-col :span="24">
              <el-form-item label="角色名称" prop="rolesName">
                <el-input v-model="ruleForm.rolesName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="角色描述" prop="content">
                <el-input v-model="ruleForm.content"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    fetchRoleList,
    delRole,
    saveCode,
    toEditRole,
    updateRole
  } from "@/api/system";
  import {
    getRoutesList,
    updateRoleName
  } from "@/api/role";
  import Pagination from "@/components/Pagination";
  import {
    Message
  } from "element-ui";
  export default {
    name: "adminuserlist",
    components: {
      Pagination
    },
    data() {
      return {
        dataList: [],
        total: 0,
        listLoading: false,
        treeLoad: false,
        listQuery: {
          page: 1,
          limit: 20,
          q_rolesName: "",
        },
        currentRow: null,
        currentRole: [],
        dialogVisible: false,
        roleList: [],
        judgmentTitle: '角色添加',
        judgmentType: '1',
        dialogFormVisible: false,
        statesList: [],
        roles: [],
        ruleForm: {
          rolesName: "",
          content: ''
        },
        rules: {
          rolesName: [{
              required: true,
              message: "请输入角色名称",
              trigger: "blur"
            },
            {
              max: 20,
              message: '不能超过20个字符',
              trigger: 'blur'
            }
          ],
          content: [{
              required: true,
              message: "请输入角色描述",
              trigger: "blur"
            },
            {
              max: 20,
              message: '不能超过20个字符',
              trigger: 'blur'
            }
          ]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      handleCurrentChange(val) {
        // 选中当前行数据
        this.currentRow = val;
      },
      handleRoleChange(val) {
        this.currentRole = val
      },
      select(selection, row) {
        if (!row) return;
        if (selection.some(el => {
            return row.id === el.id
          })) {
          if (row.children) {
            row.children.map(j => {
              this.toggleSelection(j, true)
              if (j.children) {
                j.children.map(H => {
                  this.toggleSelection(H, true)
                })
              }
            })
          }
        } else {
          if (row.children) {
            row.children.map(j => {
              this.toggleSelection(j, false)
              if (j.children) {
                j.children.map(H => {
                  this.toggleSelection(H, false)
                })
              }
            })
          }
        }
      },
      toggleSelection(row, select) {
        if (row) {
          this.$nextTick(() => {
            this.$refs.roleTable && this.$refs.roleTable.toggleRowSelection(row, select)
          })
        }
      },
      //选中递归
      checkRow(data) {
        data.map(item => {
          if (item.checked == true) this.toggleSelection(item, true)
          if (!item.children) return
          item.children.map(j => {
            if (j.checked == true) {
              this.toggleSelection(j, true)
              this.toggleSelection(item, true)
            }
            if (!j.children) return
            j.children.map(k => {
              if (k.checked == true) {
                this.toggleSelection(k, true)
                this.toggleSelection(j, true)
                this.toggleSelection(item, true)
              }
            })
          })
        })
      },
      // 获取列表数据
      getList() {
        this.listLoading = true;
        fetchRoleList(this.listQuery).then((response) => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      check() {
        this.getList();
      },
      updateRoleName() {
        // 更新权限
        let ids = ''
        for (let i in this.currentRole) {
          ids += this.currentRole[i].id + ",";
        }
        this.$confirm('确定要提交吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateRoleName({
            resIds: ids,
            roleId: this.currentRow.id
          }).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              });
              this.dialogVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.data.message
              });
              this.dialogVisible = false
            }
          })
        })
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 20,
          q_rolesName: "",
        };
        this.getList();
      },
      addRole() {
        this.judgmentTitle = '角色添加'
        this.judgmentType = '1'
        this.dialogFormVisible = true;
        this.resetForm('ruleForm')
      },
      editRole() {
        if (!this.currentRow) {
          Message.error("请选择操作行。");
          return;
        }
        this.judgmentTitle = '角色编辑'
        this.judgmentType = '2'
        this.dialogFormVisible = true;
        toEditRole({
          id: this.currentRow.id
        }).then(res => {
          this.ruleForm = res.data.data.role
        })
      },
      role() {
        if (!this.currentRow) {
          Message.error("请选择操作行。");
          return;
        }
        this.treeLoad = true
        this.dialogVisible = true
        getRoutesList({
          id: this.currentRow.id
        }).then((res) => {
          this.treeLoad = false
          this.roleList = res.data.data.systemResourcesData
          this.checkRow(this.roleList)
        });
      },
      del() {
        if (!this.currentRow) {
          Message.error("请选择操作行。");
          return;
        }
        this.$confirm("确定删除吗？", "提示", {
          onfirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delRole({
            id: this.currentRow.id
          }).then((res) => {
            if (res.data.success) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.judgmentType == '1') {
              saveCode(this.ruleForm).then(res => {
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.dialogFormVisible = false;
                this.getList()
              })
            } else {
              updateRole(this.ruleForm).then(res => {
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.dialogFormVisible = false;
                this.getList()
              })
            }
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    },
  };
</script>
<style scoped>
  .filter-container .el-col-6 {
    margin-bottom: 15px;
  }

  .filter-item {
    margin-bottom: 0;
  }

  /deep/ .filter-container label {
    font-size: 14px;
    font-weight: 500;
    margin-right: 10px;
  }
</style>
